<template>
  <uni-forms
    class="login-form"
    ref="accountForm"
    :model="formData"
    :rules="accountRules"
  >
    <uni-forms-item name="account">
      <input
        type="text"
        placeholder="请输入账号"
        v-model="formData.account"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <input
        type="text"
        v-model="formData.password"
        placeholder="请输入密码"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <button class="submit-button" @click="onFormSubmit">登录</button>
  </uni-forms>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { storeToRefs } from 'pinia'
  import { onLoad } from '@dcloudio/uni-app'
  import userApi from '@/apis/user'
  import { useUserStore } from '@/stores/users.js'

  const store = useUserStore()
  const { token } = storeToRefs(store)

  // 回跳地址
  const redirectURL = ref('')
  // 跳转地址方式
  const routeType = ref('')
  // 表单数据
  const formData = reactive({
    account: '',
    password: '',
  })
  // 表单元素的 ref 属性
  const accountForm = ref()
  // 定义表单数据验证规则
  const accountRules = reactive({
    account: {
      rules: [
        { required: true, errorMessage: '请输入登录账号' },
        { pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' },
      ],
    },
  })
  onLoad((query) => {
    redirectURL.value = query.redirectURL
    routeType.value = query.routeType
  })
  // 监听表单的提交
  async function onFormSubmit() {
    try {
      // 验证通过
      const formData = await accountForm.value.validate()
      // 表单的数据
      console.log(formData)

      // 调用登录接口
      const { code, data } = await userApi.login(formData)
      // 记录用户登录成功后的状态
      token.value = data
      // 地址重定向或switchTab
      uni[routeType.value]({ url: redirectURL.value })
    } catch (err) {
      // 验证失败
      console.log(err)
    }
  }
</script>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
